#include <stdio.h>

static const char daytab[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

int day_of_year(int year, int month, int day)
{
    int i, leap;

    if(year < 0 || month < 0 || day < 0 || month > 12 || day > 31)
        return -1;
    leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    for(i = 1; i < month; i++)
        day += daytab[leap][i];
    return day;
}

int month_day(int year, int yearday, int *pmonth, int *pday)
{
    int i, leap;

    leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;

    if(leap == 1 && (year < 0 || yearday > 366))
        return -1;
    if(leap == 0 && (year < 0 || yearday > 365))
        return -1;

    for(i = 1; yearday > daytab[leap][i]; i++)
    {
        yearday -= daytab[leap][i];
    }
    *pmonth = i;
    *pday = yearday;
}

int main()
{
    int month, day, days, ret;

    days = day_of_year(2020, 2, 15);
    printf("days = %d\n", days);

    days = day_of_year(2020, 2, 35);
    printf("days = %d\n", days);

    ret = month_day(2020, 366, &month, &day);
    if(ret > 0) 
        printf("month = %d, day = %d\n", month, day);
    else
    {
        printf("Illegal parameter, please check!");
    }

    ret = month_day(2019, 366, &month, &day);
    if(ret > 0) 
        printf("month = %d, day = %d\n", month, day);
    else
    {
        printf("Illegal parameter, please check!");
    }
    
    return 0;
}